import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.json.JSONObject;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/update_book")
public class UpdateBook extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final String url = "jdbc:mysql://1.15.151.81:3306/linux_exam";
    private static final String user = "root";
    private static final String password = "1qaz@WSX#EDC";

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Authorization");

        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String number = request.getParameter("number");
        String name = request.getParameter("name");
        String author = request.getParameter("author");

        JSONObject result = new JSONObject();

        try (Connection conn = DriverManager.getConnection(url, user, password)) {
            String sql = "UPDATE t_book SET name = ?, author = ? WHERE number = ?";
            PreparedStatement pstmt = conn.prepareStatement(sql);

            pstmt.setString(1, name);
            pstmt.setString(2, author);
            pstmt.setLong(3, Long.parseLong(number));

            int rowsAffected = pstmt.executeUpdate();

            if (rowsAffected > 0) {
                result.put("success", true);
                result.put("message", "Book updated successfully");
                result.put("number", number);
                result.put("name", name);
                result.put("author", author);
            } else {
                result.put("success", false);
                result.put("error", "Failed to update book");
            }

        } catch (SQLException e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("error", "Database error: " + e.getMessage());
        } catch (NumberFormatException e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("error", "Invalid number format");
        }

        out.print(result.toString());
    }
}
